//权限相关操作
import axios from 'axios';
import {Message} from 'element-ui'


/* 初始化菜单操作 */
export const initMenu = (router,store)=> {
    //如果vuex的状态管理中存在路由信息，则不需要再次请求
    if (store.state.children.length > 0) {
      window.console.log("状态管理器中存在路由信息.....")
      return;
    }
    console.log("用户信息:"+JSON.parse(sessionStorage.getItem("user")).empName);
    if(JSON.parse(sessionStorage.getItem("user")) != null || store.state.user.empName !=null){
      let uid = JSON.parse(sessionStorage.getItem('user')).employeesId;
      axios.get("http://localhost:8088/user/router?employeesId="+uid).then(resp=> {
        if (resp && resp.status == 200) {
          let res = resp.data;
          if(res.length>0){
            //1、对后台查询到的菜单信息，就行格式化，主要目的是：要符合Vue的路由的要求
            var fmtRoutes = formatRoutes(res);
            //2、将菜单信息，添加到路由对象中
            router.addRoutes(fmtRoutes);
            //3、调用./src/store/index.js中的方法initMenu，参数是格式化之后的菜单数组
            window.console.log("路由提交成功1");
            store.commit('initMenu',fmtRoutes);
            window.console.log("路由提交成功");
          }else{
            Message.warning({message:"失败"});
            router.replace({path: '/'});
          }

        }
      })
    }


}

export const formatRoutes = (routes)=> {
    let fmRoutes = [];
    routes.forEach(router=> {
        let {
            path,
            name,
            component,
            meta,
            children
        } = router;
        if (children && children instanceof Array) {
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            component(resolve){
              require(['../components/' + component], resolve)
            },
            meta: meta,
            children: children
        };
        fmRoutes.push(fmRouter);
    });
    return fmRoutes;
}
